package com.streaminggbs.controller;

import com.streaminggbs.common.base.ErrorCodeException;
import com.streaminggbs.common.base.ReturnBean;
import com.streaminggbs.common.utils.FileHandler;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author LiLin
 * @Date 2020/10/19 16:17
 * @Description 文件上传管理
 */
@Api(tags = {"文件上传管理接口"})
@Slf4j
@RestController
@RequestMapping("upload")
public class UploadController {

    /** Vue.js文件上传base64*/
    @ApiOperation(value = "base64文件上传", notes = "base64文件上传")
    @RequestMapping(value="/vueUploadFilesB64", method = RequestMethod.POST)
    public ResponseEntity<ReturnBean> vueUploadFilesB64(HttpServletRequest request,
                      @ApiParam(value = "文件分区(1 临时文件)") @RequestParam(value = "type", required = true) int type
    ){
        String savePath;
        switch (type){
            case 1:
                savePath = FileHandler.TEMP_PATH;
                break;
                default:
                    savePath = FileHandler.DEFAULT_PATH;
        }

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        // 得到上传的文件
        MultipartFile mFile = multipartRequest.getFile("file");

        String originalName;
        String returnPath;
        // 若上传了文件
        if (mFile != null) {
            String saveImgName = FileHandler.saveFile(mFile, FileHandler.BATH_PATH + savePath);
            if(saveImgName == null){
                throw new ErrorCodeException(-1, "图片存储错误");
            }
            returnPath  = savePath + saveImgName;
            log.info("------------------------returnPath:" + returnPath);

            originalName = mFile.getOriginalFilename();
        }else{
            log.info("=============================mFile为空==========,请找是否有file");
            throw new ErrorCodeException(-1, "未接收到上传的文件");
        }

        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("originalName", originalName);
        resultMap.put("returnPath", returnPath);

        return new ResponseEntity<>(new ReturnBean(resultMap), HttpStatus.OK);
    }
}
